﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;

namespace Cipher.Web.MVC {
    [AttributeUsage(AttributeTargets.Method)]
    public class AuthorizeDefineAttribute : AuthorizeAttribute {
        //private TableDefinesDataContext _context = new TableDefinesDataContext();

        public string RuleName { get; set; }

        public string Rule { get; set; }

        public string Description { get; set; }

        public string Tree { get; set; }

        public AuthorizeDefineAttribute() :base(){ }

        public AuthorizeDefineAttribute(string rule)
            : base() {
            Rule = rule;
        }

        public AuthorizeDefineAttribute(string rule, string ruleName, string descrition):base() {
            Rule = rule;
            RuleName = ruleName;
            Description = descrition;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            if(string.IsNullOrEmpty(this.Rule))
                return true;

            IPrincipal user = httpContext.User;
            
            if(!user.Identity.IsAuthenticated)
                return false;

            if(user.IsInRole("Admin"))
                return true;

            //var roles = (from m in _context.RoleAuthorizationMaps
            //          where m.Rule == this.Rule
            //          select m.RoleName).ToList();

            //foreach(string r in roles) {
            //    if(user.IsInRole(r))
            //        return true;
            //}

            return false;
        }

        public override void OnAuthorization(AuthorizationContext filterContext) {
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {

            base.HandleUnauthorizedRequest(filterContext);

            ViewResult result = new ViewResult();
            //result.ViewBag.Controller = filterContext.RequestContext.
            result.ViewName = "UnAuthorizated";
            //result.m
            filterContext.Result = result;
        }
    }
}